<template>
  <div>
    <a-modal title="物流下单" :visible="visible" @open="open" @ok.stop="handleOk" @cancel="handleCancel" :align-center="false" title-align="start" width="900px" :mask-closable="false">
      <a-tabs v-model:active-key="currentPage" @tab-click="changeTab">
        <a-tab-pane key="1" title="API对接的物流商">
          <div class="top mt10">
            <span>物流渠道：</span>
            <a-select size="mini" @change="getChannel" v-model="feeForm.provider" placeholder="请选择供应商" style="width: 140px" allow-search>
              <a-option v-for="item of apiExpressProvider" :key="item.id" :label="item.expressName" :value="item.id"></a-option>
            </a-select>
            <a-select class="ml10" size="mini" v-model="feeForm.channelId" placeholder="请选择物流渠道" style="width: 140px" allow-search>
              <a-option v-for="item of channelList" :key="item.id" :label="item.name" :value="item.id"></a-option>
            </a-select>

            <span class="ml10">发货地址：</span>
            <a-select class="ml10" size="mini" v-model="feeForm.address" placeholder="请选择发货地址" style="width: 140px" allow-search>
              <a-option v-for="item of addressList" :key="item.id" :label="item.name" :value="item.id"></a-option>
            </a-select>

            <a-button type="primary" class="ml10">估算费用</a-button>
            <a-button type="primary" class="ml10" @click="setTariffInfo">批量设置报关信息</a-button>
          </div>
          <a-table size="mini" class="table-two-line mt10" row-key="id" :pagination="false" v-model:selected-keys="rowSelectIds" :data="dataList" :scroll="{ y: '500px' }">
            <template #columns>
              <a-table-column title="序号" #cell="{ record, rowIndex }" :width="40">
                {{ rowIndex + 1 }}
              </a-table-column>
              <a-table-column title="平台订单号/包裹号" #cell="{ record, rowIndex }" :width="140">
                <TextLimit position="top" :rows="1">{{ $extract(record, 'order.platformOrderNumber') }}</TextLimit>
                <TextLimit position="top" :rows="1">{{ record.packageNumber }}</TextLimit>
              </a-table-column>
              <a-table-column title="承诺发货时间" #cell="{ record, rowIndex }" :width="140">
                {{ $setTime($extract(record, 'order.gmtLatestShip')) }}
              </a-table-column>
              <a-table-column title="发货仓" #cell="{ record, rowIndex }" :width="120"> <!-- {{ rowIndex + 1 }} -->-- </a-table-column>
              <a-table-column title="收件人" #cell="{ record, rowIndex }" :width="100">
                {{ $extract(record, 'order.address.userName') }}
              </a-table-column>
              <a-table-column title="国家" #cell="{ record, rowIndex }" :width="100">
                {{ $extract(record, 'order.address.country') }}
              </a-table-column>
              <a-table-column title="省州/城市" #cell="{ record, rowIndex }" :width="100">
                {{ $extract(record, 'order.address.stateOrRegion') }}
              </a-table-column>
              <a-table-column title="预估费用" #cell="{ record, rowIndex }" :width="100">
                --
                <!-- {{ rowIndex + 1 }} -->
              </a-table-column>
              <a-table-column title="报关信息" #cell="{ record, rowIndex }" :width="80" fixed="right">
                <div @click="tariffInfo.visible = true" :class="['icon', 'icon-tianjiajihua', isLogistics(record) ? 'highlight' : 'no-active']"></div>
              </a-table-column>
              <a-table-column title="操作" #cell="{ record, rowIndex }" :width="60" fixed="right">
                <a-button type="text" @click="dataList.splice(rowIndex, 1)">移除</a-button>
              </a-table-column>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="2" title="自定义物流商">
          <div class="top mt10">
            <span>物流渠道：</span>
            <a-select size="mini" @change="getChannel" v-model="feeForm.provider" placeholder="请选择供应商" style="width: 140px" allow-search>
              <a-option v-for="item of customExpressProvider" :key="item.id" :label="item.expressName" :value="item.id"></a-option>
            </a-select>
            <a-select class="ml10" size="mini" v-model="feeForm.channelId" placeholder="请选择物流渠道" style="width: 140px" allow-search>
              <a-option v-for="item of channelList" :key="item.id" :label="item.name" :value="item.id"></a-option>
            </a-select>

            <span class="ml10">发货地址：</span>
            <a-select class="ml10" size="mini" v-model="feeForm.address" placeholder="请选择发货地址" style="width: 140px" allow-search>
              <a-option v-for="item of addressList" :key="item.id" :label="item.name" :value="item.id"></a-option>
            </a-select>
          </div>

          <a-table size="mini" class="table-two-line mt10" :pagination="false" :data="customDataList" :scroll="{ y: '500px' }">
            <template #columns>
              <a-table-column title="序号" #cell="{ record, rowIndex }" :width="40">
                {{ rowIndex }}
              </a-table-column>
              <a-table-column title="平台订单号/包裹号" #cell="{ record, rowIndex }" :width="140">
                <TextLimit position="top" :rows="1">{{ $extract(record, 'order.platformOrderNumber') }}</TextLimit>
                <TextLimit position="top" :rows="1">{{ record.packageNumber }}</TextLimit>
              </a-table-column>
              <a-table-column title="承诺发货时间" #cell="{ record, rowIndex }" :width="140">
                {{ $setTime($extract(record, 'order.gmtLatestShip')) }}
              </a-table-column>
              <a-table-column title="发货仓" #cell="{ record, rowIndex }" :width="120">
                --
                <!-- {{ rowIndex + 1 }} -->
              </a-table-column>
              <a-table-column title="收件人" #cell="{ record, rowIndex }" :width="100">
                {{ $extract(record, 'order.address.userName') }}
              </a-table-column>
              <a-table-column title="国家" #cell="{ record, rowIndex }" :width="100">
                {{ $extract(record, 'order.address.country') }}
              </a-table-column>
              <a-table-column title="省州/城市" #cell="{ record, rowIndex }" :width="100">
                {{ $extract(record, 'order.address.stateOrRegion') }}
              </a-table-column>
              <a-table-column :width="130" fixed="right">
                <template #title>
                  <div class="required">预估费用</div>
                </template>
                <template #cell="{ record, rowIndex }">
                  <a-input-number v-model="record.amtShip" class="fl" hide-button :style="{ width: '90px' }" />
                  <icon-arrow-fall @click="setAmtShip(record.amtShip)" v-if="rowIndex == 0" class="arrow-icon fl" />
                </template>
              </a-table-column>
              <a-table-column :width="100" fixed="right">
                <template #title>
                  <div class="required">运单号</div>
                </template>
                <template #cell="{ record, rowIndex }">
                  <a-input v-model="record.waybillNumber" class="fl" :style="{ width: '90px' }" />
                </template>
              </a-table-column>
              <a-table-column :width="100" fixed="right">
                <template #title>
                  <div class="required">跟踪号</div>
                </template>
                <template #cell="{ record, rowIndex }">
                  <a-input v-model="record.trackingNumber" class="fl" :style="{ width: '90px' }" />
                </template>
              </a-table-column>
              <a-table-column :width="120" title="物流面单" fixed="right">
                <template #cell="{ record, rowIndex }">
                  <div style="display: flex">
                    <a-upload size="mini" action="#" :auto-upload="false" @before-upload="beforeUpload($event, rowIndex)">
                      <template #upload-button>
                        <a-button type="primary" style="width: 80px">
                          {{ record.labelUrl ? '已上传' : '点击上传' }}
                        </a-button>
                      </template>
                    </a-upload>
                    <icon-close-circle-fill v-if="record.labelUrl" @click="record.labelUrl = ''" style="font-size: 18px; margin-top: 5px; cursor: pointer" />
                  </div>
                </template>
              </a-table-column>
              <a-table-column title="操作" #cell="{ record, rowIndex }" :width="40" fixed="right">
                <a-button type="text" @click="customDataList.splice(rowIndex, 1)">移除</a-button>
              </a-table-column>
            </template>
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
  </div>

  <TariffInfo ref="tariffInfo" :selectRow="dataList" @save="getPackageList" />
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, computed } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { upload } from '@/api/base'
  import { listExpressProvider, pageExpressChannel, pageExpressAddress } from '@/api/warehouse'
  import { createOrderShip, updatePackageShip, listPackage } from '@/api/order'
  import TariffInfo from './tariffInfo.vue'
  import _ from 'lodash-es'
  export default defineComponent({
    props: ['ids'],
    components: { TariffInfo },
    setup(props: any, { emit }) {
      let visible = ref(false)
      const tariffInfo = ref()
      const data: any = reactive({
        currentPage: '1',
        apiExpressProvider: [],
        customExpressProvider: [],
        channelList: [],
        addressList: [],
        feeForm: {
          provider: '',
          channelId: '',
          address: '',
        },
        dataList: [],
        customDataList: [],
        rowSelection: {
          type: 'checkbox',
          showCheckedAll: true,
          onlyCurrent: false,
        },
        rowSelectIds: [],
        packageList: [],
      })

      const open = () => {
        getProvider()
        getAddress()
        getPackageList()
        // createPackage()
        // console.log(props.ids)
      }
      const handleOk = async () => {
        if (!data.feeForm.provider) {
          return Message.error('请选择供应商')
        }
        if (!data.feeForm.channelId) {
          return Message.error('请选择渠道')
        }
        if (!data.feeForm.address) {
          return Message.error('请选择发货地址')
        }
        let params: any = {}

        try {
          data.loading = true
          let res: any = {}
          if (data.currentPage == '1') {
            params = {
              expressChannelId: data.feeForm.channelId,
              expressProviderId: data.feeForm.provider,
              shipAddressId: data.feeForm.address,
              packageList: [],
            }
            data.dataList.forEach((e: any) => {
              let obj: any = {}
              obj.id = e.id
              obj.platform = e.platform
              params.packageList.push(obj)
            })
            res = await createOrderShip(params)
          } else {
            params = {
              expressChannelId: data.feeForm.channelId,
              expressProviderId: data.feeForm.provider,
              shipAddressId: data.feeForm.address,
              packageList: [],
            }
            data.customDataList.forEach((e: any) => {
              let obj = {
                amtShip: e.amtShip,
                id: e.id,
                labelUrl: e.labelUrl ? e.labelUrl : '',
                trackingNumber: e.trackingNumber,
                platform: e.platform,
                waybillNumber: e.waybillNumber,
              }
              params.packageList.push(obj)
            })
            res = await updatePackageShip(params)
          }
          data.feeForm = {
            provider: '',
            channelId: '',
            address: '',
          }
          if (res.code == 'SUCCESS') {
            Message.success('物流下单成功')
            visible.value = false
            emit('save')
          }
          data.loading = false
        } catch (error) {
          data.loading = false
        }
      }
      const handleCancel = () => {
        data.feeForm = {
          provider: '',
          channelId: '',
          address: '',
        }
        emit('save')
        visible.value = false
      }

      // const createPackage = () => {
      //   data.packageList = []
      //   props.selectRow.forEach((e: any) => {
      //     let obj = _.cloneDeep(e)
      //     delete obj.packageList
      //     delete obj.remarkList
      //     delete obj.tagList
      //     delete obj.id

      //     e.packageList.forEach((el: any) => {
      //       let newObj = { ...obj, ...el }
      //       newObj.platform = e.platform
      //       data.packageList.push(newObj)
      //     })
      //   })
      //   console.log(data.packageList)

      //   data.dataList = _.cloneDeep(data.packageList)
      //   data.customDataList = _.cloneDeep(data.packageList)
      // }

      const getPackageList = async () => {
        const res = await listPackage({ idList: props.ids.join(',') })
        data.dataList = _.cloneDeep(res?.data || [])
        data.customDataList = _.cloneDeep(res?.data || [])
      }

      const getProvider = async () => {
        const res: any = await listExpressProvider()
        if (res.code == 'SUCCESS') {
          let arr = res?.data || []
          data.apiExpressProvider = arr.filter((e: any) => e.providerType == 'api')
          data.customExpressProvider = arr.filter((e: any) => e.providerType == 'custom')
          // data.feeForm.provider = data.currentPage == 1 ? data.apiExpressProvider[0]?.id || '' : data.customExpressProvider[0]?.id || ''
          // getChannel()
        }
      }

      const getChannel = async () => {
        let params = {
          expressProviderId: data.feeForm.provider,
          pageNum: 1,
          pageSize: 9999,
        }
        const res: any = await pageExpressChannel(params)
        data.channelList = res?.data?.records || []
      }

      const getAddress = async () => {
        let params = {
          pageNum: 1,
          pageSize: 9999,
        }
        const res = await pageExpressAddress(params)
        let arr = res?.data?.records || []
        data.addressList = arr.filter((e: any) => e.type == 'ship')
      }

      const setTariffInfo = () => {
        // if (data.rowSelectIds.length <= 0) {
        //   return Message.error('请选择需要操作的数据')
        // }
        tariffInfo.value.visible = true
      }

      const changeTab = (index: string) => {
        data.feeForm = {
          provider: '',
          channelId: '',
          address: '',
        }
        // if (index == '1') {
        //   data.feeForm.provider = data.apiExpressProvider[0].id
        // } else {
        //   data.feeForm.provider = data.customExpressProvider[0].id
        // }
        // getChannel()
      }

      const isLogistics = (item: any) => {
        let flag = false
        item.packageItemList.forEach((e: any) => {
          if (e.declaration && e.declaration.name) {
            flag = true
          }
        })
        return flag
      }

      const beforeUpload = async (file: any, index: string) => {
        const extension = file.name.substring(file.name.lastIndexOf('.') + 1)
        console.log(index)

        if (!['xls', 'xlsx', 'pdf'].includes(extension)) {
          Message.error('只能上传excel,pdf文件')
          return
        }

        let formData = new FormData()
        formData.append('file', file)
        const res = await upload(formData)
        // // item.labelUrl = res?.data?.publicUrl
        data.customDataList[index].labelUrl = res?.data?.publicUrl
      }

      const setAmtShip = (num: string | number) => {
        data.customDataList.map((e: any) => {
          e.amtShip = num
        })
      }

      return {
        ...(toRefs(data) as any),
        visible,
        open,
        handleOk,
        handleCancel,
        getChannel,
        tariffInfo,
        setTariffInfo,
        changeTab,
        isLogistics,
        beforeUpload,
        setAmtShip,
        getPackageList,
      }
    },
  })
</script>

<style lang="less" scoped>
  .arrow-icon {
    font-size: 24px;
    margin-top: 3px;
  }

  .top {
    display: flex;
    height: 30px;
    line-height: 30px;
    // border: 1px solid #d7d7d7;
  }

  .icon-tianjiajihua {
    font-size: 20px;
    cursor: pointer;
    user-select: none;
  }

  .no-active {
    color: #aaaaaa;
  }
</style>
